#include "libmri.h"

template<> void cmdline_arg_t<int>::
get_value (char const *s){ val = atoi(s); }

template<> char const* cmdline_arg_t<int>:: 
type_string(){ return "int"; }


template<> void cmdline_arg_t<float>::
get_value (char const *s){ val = atof(s); }

template<> char const* cmdline_arg_t<float>:: 
type_string(){ return "float"; }


template<> void cmdline_arg_t<double>::
get_value (char const *s){ val = atof(s); }

template<> char const* cmdline_arg_t<double>:: 
type_string(){ return "double"; }


template<> void cmdline_arg_t<char*>::
get_value (char const *s){ val = strdup(s); }

template<> char const* cmdline_arg_t<char*>:: 
type_string(){ return "char*"; }


template<> void cmdline_arg_t<bool>::
get_value (char const *s){
	val = (!s) or (!strcmp(s, "yes") or !strcmp(s, "true"));
}

template<> char const* cmdline_arg_t<bool>::
type_string(){ return "bool"; }


template<> void cmdline_arg_t<shm_array_t*>::
get_value (char const *key){
	if (get_shm_array (key, &val)){
		throw arg_parsing_exception ();
	}
}

template<> char const* cmdline_arg_t<shm_array_t*>::
type_string(){ return "shm_array_t*"; }



extern void get_args (struct cmdline_arg *args[],
                             char const *argstring,
                             char const *argsep)
{
	char *as, *s, **ss, *tmp;
	int argc;
	char **argv;

	as = strdup (argstring);
	s = as; ss = &s;

	argc = 1; while (strsep(ss, argsep)) ++argc;

	argv = new char*[argc];
	argv[0] = 0;

	free (as); as = strdup(argstring);
	s = as; ss = &s;

	argc = 1; while ((tmp = strsep(ss, argsep))) argv[argc++] = tmp;

	for (int a = 1; a < argc; ++a)
	{
		char *t0 = strdup (argv[a]), *t = t0, **tt = &t;

		char *name = strsep (tt, "=");
		char *val = strsep (tt, "=");

		for (int aa = 0; args[aa]; ++aa){
			if (!strcmp(args[aa]->name, name)){
				args[aa]->get_value (val);
				args[aa]->set = true;
			}
		}

		free (t0);
	}

	free (as);
	delete [] argv;
}
